<template>
  <div class="add-car-container">
    <el-card class="add-car-card">
      <template #header>
        <div class="card-header">
          <span>添加车辆详细信息</span>
        </div>
      </template>

      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
        class="add-car-form"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产年份" prop="productyear">
              <el-input v-model="form.productyear"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车辆等级" prop="level">
              <el-input v-model="form.level"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="座位数" prop="seats">
              <el-input-number
                v-model="form.seats"
                :min="1"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车门数" prop="doors">
              <el-input-number
                v-model="form.doors"
                :min="1"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="能源类型" prop="energyid">
              <el-select
                v-model="form.energyid"
                placeholder="请选择能源类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in energyOptions"
                  :key="item.energeid"
                  :label="item.energename"
                  :value="item.energeid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="变速箱类型" prop="gearid">
              <el-select
                v-model="form.gearid"
                placeholder="请选择变速箱类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in gearOptions"
                  :key="item.gearid"
                  :label="item.gearname"
                  :value="item.gearid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排量" prop="displacement">
              <el-input v-model="form.displacement"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="驱动方式" prop="drive">
              <el-input v-model="form.drive"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电动天窗" prop="upwindow">
              <el-radio-group v-model="form.upwindow">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="倒车雷达" prop="radar">
              <el-radio-group v-model="form.radar">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="GPS导航" prop="gps">
              <el-radio-group v-model="form.gps">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="驾照要求" prop="lisence">
              <el-radio-group v-model="form.lisence">
                <el-radio :label="0">无</el-radio>
                <el-radio :label="1">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件状态" prop="fsfile">
              <el-radio-group v-model="form.fsfile">
                <el-radio :label="0">未上传</el-radio>
                <el-radio :label="1">已上传</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否删除" prop="isdeleted">
              <el-radio-group v-model="form.isdeleted">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否上线" prop="isonline">
              <el-radio-group v-model="form.isonline">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车辆类型" prop="carid">
              <el-select
                v-model="form.carid"
                placeholder="请选择车辆类型"
                style="width: 100%"
                @change="handleCarChange"
              >
                <el-option
                  v-for="item in carOptions"
                  :key="item.carid"
                  :label="item.carname"
                  :value="item.carid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="plate">
              <el-input v-model="form.plate"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="车辆实拍图片" prop="photos">
          <el-upload
            action="http://localhost:9999/oss/updateAvatar"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            :auto-upload="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >提交</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "@/util/service";
import { useLoginStore } from "@/stores/userStores";

const userStore = useLoginStore();

// 表单引用
const ruleFormRef = ref();

// 表单数据
const form = reactive({
  productyear: "",
  level: "",
  seats: null,
  doors: null,
  energyid: null,
  gearid: null,
  displacement: "",
  drive: null,
  upwindow: null,
  radar: null,
  gps: null,
  carid: null,
  lisence: null,
  fsfile: null,
  isdeleted: null,
  isonline: null,
  userid: userStore.getId,
  plate: "",
  photos: [], // 存储图片对象数组 [{ cpid: 0, cpimg: '图片地址' }]
});

// 表单验证规则
const rules = {
  productyear: [{ required: true, message: "请输入生产年份", trigger: "blur" }],
  level: [{ required: true, message: "请输入车辆等级", trigger: "blur" }],
  seats: [{ required: true, message: "请输入座位数", trigger: "blur" }],
  doors: [{ required: true, message: "请输入车门数", trigger: "blur" }],
  energyid: [{ required: true, message: "请选择能源类型", trigger: "change" }],
  gearid: [{ required: true, message: "请选择变速箱类型", trigger: "change" }],
  displacement: [{ required: true, message: "请输入排量", trigger: "blur" }],
  drive: [{ required: true, message: "请输入驱动方式", trigger: "blur" }],
  upwindow: [{ required: true, message: "请选择电动天窗", trigger: "change" }],
  radar: [{ required: true, message: "请选择倒车雷达", trigger: "change" }],
  gps: [{ required: true, message: "请选择GPS导航", trigger: "change" }],
  carid: [{ required: true, message: "请选择车辆类型", trigger: "change" }],
  lisence: [{ required: true, message: "请选择驾照要求", trigger: "change" }],
  fsfile: [{ required: true, message: "请选择文件状态", trigger: "change" }],
  isdeleted: [{ required: true, message: "请选择是否删除", trigger: "change" }],
  isonline: [{ required: true, message: "请选择是否上线", trigger: "change" }],
  userId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
  plate: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
  photos: [
    { required: true, message: "请上传车辆实拍图片", trigger: "change" },
  ],
};

// 能源类型选项
const energyOptions = ref([]);

// 变速箱类型选项
const gearOptions = ref([]);

// 车辆类型选项
const carOptions = ref([]);

// 图片上传相关
const fileList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

// 获取能源类型选项
const getEnergyOptions = async () => {
  try {
    const res = await api.get("/tcardateil/getEnerge");
    energyOptions.value = res.data;
  } catch (error) {
    console.error("获取能源类型失败:", error);
    ElMessage.error("获取能源类型失败");
  }
};

// 获取变速箱类型选项
const getGearOptions = async () => {
  try {
    const res = await api.get("/tcardateil/getTransmission");
    gearOptions.value = res.data;
  } catch (error) {
    console.error("获取变速箱类型失败:", error);
    ElMessage.error("获取变速箱类型失败");
  }
};

// 获取车辆类型选项
const getCarOptions = async () => {
  try {
    const res = await api.get("/tcar/selectCarBySellerId", {
      params: {
        sellerId: userStore.getId,
      },
    });
    if (res.code === 200 && res.data) {
      carOptions.value = res.data;
    } else {
      ElMessage.error("获取车辆类型失败");
    }
  } catch (error) {
    console.error("获取车辆类型失败:", error);
    ElMessage.error("获取车辆类型失败");
  }
};

// 图片上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  console.log("上传成功:", response);
  // 假设后端返回的图片地址在 response.data 中
  if (response && response.data) {
    // 将图片信息作为对象添加到表单的 photos 数组中
    form.photos.push({
      cpid: 0,
      cpimg: response.data,
    });
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败");
  }
};

// 移除图片
const handleRemove = (file, fileList) => {
  console.log("移除文件:", file);
  // 从表单的 photos 数组中移除对应的图片对象
  const index = form.photos.findIndex((item) => item.cpimg === file.url);
  if (index !== -1) {
    form.photos.splice(index, 1);
  }
};

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 车辆选择变化时的处理
const handleCarChange = (value) => {
  console.log("选择的车辆ID:", value);
};

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 提交表单数据，包括图片对象数组
      api
        .post("/tcardateil/insertCarDateil", form)
        .then((res) => {
          if (res.code === 200) {
            ElMessage({
              message: "提交成功",
              type: "success",
            });
            // 提交成功后重置表单
            resetForm(formEl);
          } else {
            ElMessage({
              message: res.message || "提交失败",
              type: "error",
            });
          }
        })
        .catch((error) => {
          console.error("提交失败:", error);
          ElMessage({
            message: "提交失败，请重试",
            type: "error",
          });
        });
    } else {
      console.log("error submit!!", fields);
      ElMessage({
        message: "请检查必填项",
        type: "warning",
      });
      return false;
    }
  });
};

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  // 重置图片相关数据
  form.photos = [];
  fileList.value = [];
};

onMounted(() => {
  getEnergyOptions();
  getGearOptions();
  getCarOptions(); // 添加这行代码
});
</script>

<style scoped>
.add-car-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
}

.add-car-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.add-car-form {
  padding: 20px;
}

.add-car-form :deep(.el-form-item__label) {
  font-weight: bold;
}

.add-car-form :deep(.el-input-number) {
  width: 100%;
}

.add-car-form :deep(.el-select) {
  width: 100%;
}

.add-car-form :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.add-car-form :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}

@media (max-width: 768px) {
  .add-car-container {
    padding: 10px;
  }

  .add-car-form {
    padding: 10px;
  }

  :deep(.el-col) {
    width: 100%;
    margin-bottom: 10px;
  }

  .add-car-form :deep(.el-form-item__label) {
    text-align: left !important;
    padding-bottom: 5px;
  }
}
</style>
